<script setup lang="ts">
import { h, onMounted, ref } from 'vue';
import {
  NButton,
  NCard,
  NDataTable,
  NEmpty,
  NForm,
  NFormItem,
  NInput,
  NInputNumber,
  NList,
  NListItem,
  NModal,
  NPopconfirm,
  NSelect,
  NSpace,
  NTag,
  NThing,
  useMessage
} from 'naive-ui';
import type { DataTableColumns } from 'naive-ui';

// 定义角色类型
interface Role {
  id: string;
  name: string;
  code: string;
  description: string;
  status: 'active' | 'inactive';
  createdAt: string;
  sort: number;
}

// 消息提示
const message = useMessage();

// 表格数据
const roles = ref<Role[]>([]);
const loading = ref(false);

// 分页相关
const pagination = ref({
  page: 1,
  pageSize: 10,
  itemCount: 0,
  showSizePicker: true,
  pageSizes: [10, 20, 30]
});

// 模态框相关
const showModal = ref(false);
const isEditing = ref(false);
const currentRole = ref<Partial<Role>>({});

// 状态选项
const statusOptions = [
  { label: '激活', value: 'active' },
  { label: '禁用', value: 'inactive' }
];

// 编辑角色
const handleEdit = (role: Role) => {
  isEditing.value = true;
  currentRole.value = { ...role };
  showModal.value = true;
};

// 删除角色
const handleDelete = (id: string) => {
  roles.value = roles.value.filter(role => role.id !== id);
  message.success('删除成功');
};

// 表格列定义
const createColumns = (): DataTableColumns<Role> => {
  return [
    {
      title: '角色名称',
      key: 'name'
    },
    {
      title: '角色编码',
      key: 'code'
    },
    {
      title: '描述',
      key: 'description'
    },
    {
      title: '排序',
      key: 'sort'
    },
    {
      title: '状态',
      key: 'status',
      render(row) {
        return h(
          NTag,
          { type: row.status === 'active' ? 'success' : 'error' },
          { default: () => (row.status === 'active' ? '激活' : '禁用') }
        );
      }
    },
    {
      title: '创建时间',
      key: 'createdAt'
    },
    {
      title: '操作',
      key: 'actions',
      render(row) {
        return h(NSpace, null, {
          default: () => [
            h(
              NButton,
              {
                size: 'small',
                onClick: () => handleEdit(row)
              },
              { default: () => '编辑' }
            ),
            h(
              NPopconfirm,
              {
                onPositiveClick: () => handleDelete(row.id)
              },
              {
                default: () => '确认删除该角色吗？',
                trigger: () =>
                  h(
                    NButton,
                    {
                      size: 'small',
                      type: 'error',
                      quaternary: true
                    },
                    { default: () => '删除' }
                  )
              }
            )
          ]
        });
      }
    }
  ];
};

const columns = createColumns();

// 获取角色数据
const fetchRoles = async () => {
  loading.value = true;
  try {
    // 模拟 API 调用
    // 实际项目中应该调用真实的 API
    await new Promise(resolve => {
      setTimeout(resolve, 500);
    });

    // 模拟数据
    roles.value = [
      {
        id: '1',
        name: '管理员',
        code: 'admin',
        description: '系统管理员，拥有所有权限',
        status: 'active',
        createdAt: '2023-01-01',
        sort: 1
      },
      {
        id: '2',
        name: '普通用户',
        code: 'user',
        description: '普通用户，拥有基本权限',
        status: 'active',
        createdAt: '2023-02-01',
        sort: 2
      },
      {
        id: '3',
        name: '访客',
        code: 'guest',
        description: '访客用户，只读权限',
        status: 'inactive',
        createdAt: '2023-03-01',
        sort: 3
      },
      {
        id: '4',
        name: '财务专员',
        code: 'finance',
        description: '财务部门专用角色',
        status: 'active',
        createdAt: '2023-04-01',
        sort: 4
      },
      {
        id: '5',
        name: '人事专员',
        code: 'hr',
        description: '人事部门专用角色',
        status: 'active',
        createdAt: '2023-05-01',
        sort: 5
      }
    ];

    pagination.value.itemCount = roles.value.length;
  } catch {
    message.error('获取角色数据失败');
  } finally {
    loading.value = false;
  }
};

// 处理分页变化
const handlePageChange = (page: number) => {
  pagination.value.page = page;
  fetchRoles();
};

// 处理页面大小变化
const handlePageSizeChange = (pageSize: number) => {
  pagination.value.pageSize = pageSize;
  pagination.value.page = 1;
  fetchRoles();
};

// 新增角色
const handleAdd = () => {
  isEditing.value = false;
  currentRole.value = {};
  showModal.value = true;
};

// 保存角色
const handleSave = () => {
  if (!currentRole.value.name) {
    message.warning('请输入角色名称');
    return;
  }

  if (!currentRole.value.code) {
    message.warning('请输入角色编码');
    return;
  }

  if (isEditing.value) {
    // 编辑角色
    const index = roles.value.findIndex(role => role.id === currentRole.value.id);
    if (index !== -1) {
      roles.value[index] = { ...roles.value[index], ...currentRole.value } as Role;
      message.success('更新成功');
    }
  } else {
    // 新增角色
    const newRole: Role = {
      id: Date.now().toString(),
      name: currentRole.value.name!,
      code: currentRole.value.code!,
      description: currentRole.value.description || '',
      status: currentRole.value.status || 'active',
      createdAt: new Date().toISOString().split('T')[0],
      sort: currentRole.value.sort || 0
    };
    roles.value.unshift(newRole);
    message.success('新增成功');
  }

  showModal.value = false;
};

// 获取状态标签
const getStatusTag = (status: 'active' | 'inactive') => {
  return h(
    NTag,
    { type: status === 'active' ? 'success' : 'error', size: 'small' },
    { default: () => (status === 'active' ? '激活' : '禁用') }
  );
};

// 组件挂载时获取数据
onMounted(() => {
  fetchRoles();
});
</script>

<template>
  <div class="role-management">
    <NCard title="角色管理">
      <template #header-extra>
        <NButton type="primary" @click="handleAdd">新增角色</NButton>
      </template>

      <!-- 响应式内容区域 -->
      <div class="content-container">
        <!-- 桌面端表格视图 -->
        <div class="desktop-view">
          <NDataTable
            :columns="columns"
            :data="roles"
            :loading="loading"
            :pagination="pagination"
            remote
            @update:page="handlePageChange"
            @update:page-size="handlePageSizeChange"
          />
        </div>

        <!-- 移动端卡片视图 -->
        <div class="mobile-view">
          <NList v-if="roles.length > 0" class="mobile-list">
            <NListItem v-for="role in roles" :key="role.id">
              <NThing>
                <template #header>
                  <span class="role-name">{{ role.name }}</span>
                </template>
                <template #header-extra>
                  <NSpace>
                    <NButton size="tiny" @click="handleEdit(role)">编辑</NButton>
                    <NPopconfirm @positive-click="handleDelete(role.id)">
                      <template #trigger>
                        <NButton size="tiny" type="error" quaternary>删除</NButton>
                      </template>
                      确认删除该角色吗？
                    </NPopconfirm>
                  </NSpace>
                </template>

                <div class="role-info-grid">
                  <div class="role-info-item">
                    <div class="role-info-label">编码:</div>
                    <div class="role-info-value">{{ role.code }}</div>
                  </div>
                  <div class="role-info-item">
                    <div class="role-info-label">排序:</div>
                    <div class="role-info-value">{{ role.sort }}</div>
                  </div>
                  <div class="role-info-item">
                    <div class="role-info-label">状态:</div>
                    <div class="role-info-value">
                      <component :is="getStatusTag(role.status)" />
                    </div>
                  </div>
                  <div class="role-info-item">
                    <div class="role-info-label">创建时间:</div>
                    <div class="role-info-value">{{ role.createdAt }}</div>
                  </div>
                  <div v-if="role.description" class="role-info-item">
                    <div class="role-info-label">描述:</div>
                    <div class="role-info-value">{{ role.description }}</div>
                  </div>
                </div>
              </NThing>
            </NListItem>
          </NList>

          <!-- 空状态 -->
          <NEmpty v-else description="暂无角色数据" />
        </div>
      </div>
    </NCard>

    <!-- 角色编辑/新增模态框 -->
    <NModal v-model:show="showModal" preset="card" class="role-modal" title="角色信息">
      <NForm :model="currentRole" label-placement="left" label-width="80">
        <NFormItem label="角色名称" path="name">
          <NInput v-model:value="currentRole.name" placeholder="请输入角色名称" />
        </NFormItem>

        <NFormItem label="角色编码" path="code">
          <NInput v-model:value="currentRole.code" placeholder="请输入角色编码" />
        </NFormItem>

        <NFormItem label="描述" path="description">
          <NInput v-model:value="currentRole.description" placeholder="请输入描述" type="textarea" />
        </NFormItem>

        <NFormItem label="排序" path="sort">
          <NInputNumber v-model:value="currentRole.sort" placeholder="请输入排序值" />
        </NFormItem>

        <NFormItem label="状态" path="status">
          <NSelect v-model:value="currentRole.status" :options="statusOptions" placeholder="请选择状态" />
        </NFormItem>
      </NForm>

      <template #footer>
        <NSpace justify="end">
          <NButton @click="showModal = false">取消</NButton>
          <NButton type="primary" @click="handleSave">保存</NButton>
        </NSpace>
      </template>
    </NModal>
  </div>
</template>

<style scoped>
.role-management {
  padding: 16px;
}

.n-card {
  margin-bottom: 16px;
}

.content-container {
  width: 100%;
}

/* 桌面端视图 - 默认显示 */
.desktop-view {
  display: block;
}

.mobile-view {
  display: none;
}

.mobile-list {
  background-color: transparent;
}

.role-modal {
  width: 90%;
  max-width: 500px;
}

.role-name {
  font-weight: bold;
}

.role-info-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 8px;
  margin-top: 8px;
}

.role-info-item {
  display: flex;
  flex-direction: column;
}

.role-info-label {
  font-size: 12px;
  color: #999;
}

.role-info-value {
  font-size: 14px;
  margin-top: 2px;
}

/* 移动端适配 - 当屏幕宽度小于等于768px时 */
@media (max-width: 768px) {
  .desktop-view {
    display: none;
  }

  .mobile-view {
    display: block;
  }

  .role-info-grid {
    grid-template-columns: 1fr;
  }

  .role-management {
    padding: 8px;
  }

  /* 移动端卡片样式优化 */
  :deep(.n-list-item) {
    padding: 12px 0;
    border-bottom: 1px solid var(--n-border-color);
  }

  :deep(.n-list-item:last-child) {
    border-bottom: none;
  }

  :deep(.n-thing-main__) {
    padding: 0;
  }
}
</style>
